<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>成品销售</title>
</head>

<body>
  <div id="app">
    <div class="product-sale" v-loading.fullscreen.lock="loading">
      <search-btn-view ref="searchBtnView" btn-text="订单查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button size="medium" type="primary" @click="addCustomer">添加客户</el-button>
          <template v-if="selectProductList.length>0">
            <el-button size="medium" type="primary" @click="outWarehouseList(false)">批量出库</el-button>
            <el-button size="medium" type="primary" @click="outWarehouseList(true)" :disabled="!selfApprovalPermission">批量审核过账</el-button>
          </template>
        </template>
        <div slot="search-content">
          <sys-common-search ref="commonSearch" :search="search" request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:13}"
            :search-field="searchField" label-width="100px" input-width="220px">
          </sys-common-search>
        </div>
      </search-btn-view>
      <div class="product-sale-table-div">
        <el-table fit stripe border :data="productList" height="parent" :cell-class-name="tableCellClass" @row-click="tableRowClick"
          @selection-change="toSelectProductList">
          <el-table-column fixed :resizable="false" type="selection" width="40" align="center"></el-table-column>
          <el-table-column fixed sortable :resizable="false" prop="type" label="类型" width="80px" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.listMaterial.length===0">
                <div>{{i18n.getMsg(`warehouse.warehouseOrderType.${scope.row.type}`)}}</div>
              </div>
              <el-popover v-else title="订单物料颜色" trigger="hover" placement="right-start">
                <div slot="reference">
                  <div style="height:30px;line-height:30px;">
                    {{i18n.getMsg(`warehouse.warehouseOrderType.${scope.row.type}`)}}
                  </div>
                </div>
                <div>
                  <div v-for="(material,index) in scope.row.listMaterial" key="`material_${index}`">
                    <span>{{material.materialType}}</span>
                    <span v-if="material.colorDescription!==''">- {{material.colorDescription}}</span>
                  </div>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column sortable prop="companyOrderId" label="订单编号" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column sortable prop="factoryId" label="工厂型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable prop="coustomId" label="客户型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable prop="rowIndexs" label="订单序号" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.rowIndexs===-1?globalConfig.orderDefaultRowIndex:scope.row.rowIndexs}}</span>
            </template>
          </el-table-column>
          <el-table-column sortable prop="orderCustomerName" label="客户" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column sortable prop="stockCount" label="库存" min-width="100px" align="center">
          </el-table-column>
          <el-table-column sortable prop="orderRowCount" label="订单数" min-width="100px" align="center">
          </el-table-column>
          <el-table-column sortable prop="realCount" label="已出库数" min-width="100px" align="center">
          </el-table-column>
          <el-table-column :resizable="false" label="出库客户" width="140px" header-align="center">
            <template slot-scope="scope">
              <el-select filterable size="small" v-model="scope.row.customerName" style="width:130px" placeholder="请选择客户">
                <el-option v-for="customerName in customerNameList" :label="customerName" :value="customerName">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="出库单价" width="140px" header-align="center">
            <template slot-scope="scope">
              <el-input-number size="small" v-model="scope.row.outCountPrice" :min="0" :max="9999999999.99" :precision="4" :controls="false"
                placeholder="请输入出库单价" @change="unitPriceChange(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="出库数量" width="140px" header-align="center">
            <template slot-scope="scope">
              <el-input-number size="small" v-model="scope.row.count" :min="1" :max="9999999999" :precision="0" :controls="false"
                placeholder="请输入出库数量" @change="unitPriceChange(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="出库单位" width="100px" header-align="center">
            <template slot-scope="scope">
              <el-select size="small" filterable v-model="scope.row.inOutUnit">
                <el-option v-for="unit in unitList" :key="unit" :value="unit"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="金额" width="140px" header-align="center">
            <template slot-scope="scope">
              <el-input-number style="width:130px" size="small" v-model="scope.row.inOutMoney" :min="0" :precision="2" :controls="false"
                placeholder="请输入金额" @change="totalMoneyChange(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="备注" width="240px" header-align="center">
            <template slot-scope="scope">
              <el-input size="small" v-model="scope.row.remark" :maxlength="15" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="分期情况" min-width="210px" header-align="center">
            <template slot-scope="scope">
              <div class="product-sale-instalment" @click="toInstalmentOut(scope.row)">
                <div v-if="scope.row.instalmentInfo===null" style="text-align:center">
                  <a href="javascript:void(0);">不分期</a>
                </div>
                <div v-else>
                  <a href="javascript:void(0);">
                    分期间隔{{scope.row.instalmentInfo.stagesInterval}}个月，共分{{scope.row.instalmentInfo.stagesCount}}次分期
                  </a>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="操作" width="160px" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="outWarehouse(scope.row,false)">出库</el-button>
              <el-button type="primary" size="small" @click="outWarehouse(scope.row,true)" :disabled="!selfApprovalPermission">审核过账</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>
    </div>

    <el-dialog title="成品出库明细" :visible.sync="openDetailDialog" top="15vh">
      <div style="height:calc(70vh - 54px);overflow:auto;">
        <out-warehouse-detail v-if="openDetailDialog" :product="selectProduct"></out-warehouse-detail>
      </div>
    </el-dialog>

    <el-dialog title="添加客户" :visible.sync="openCustomerDialog" top="10vh" @closed="customer=null">
      <div style="height:calc(80vh - 54px);overflow:auto;">
        <customer-form v-if="openCustomerDialog" :customer-type="2" :customer="customer" @save-success="addCustomerSuccess">
        </customer-form>
      </div>
    </el-dialog>

    <el-dialog title="出库分期设置" :visible.sync="openInstalmentDialog" top="calc(50vh - 137px)" width="350px" @closed="instalmentDialogClosed">
      <div style="height:220px;overflow:auto">
        <instalment-out v-if="openInstalmentDialog" :order="instalmentOrder" @instalment-success="instalmentSuccess"></instalment-out>
      </div>
    </el-dialog>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/sysCommonSearch.css",
    "/vueSystem/components/css/searchBtnView.css",
    "/warehouse/finishProductOut/instalmentOut/instalmentOut.css"
  ], [
    "/vueSystem/i18n/index.js",
    "/vueSystem/js/permissionUtil.js",
    "/vueSystem/js/dropdownUtil.js",
    "/vueSystem/js/checkVaildUtil.js",
    "/vueSystem/components/sysCommonSearch.js",
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/models/baseModel.js",
    "/purchaseOrder/models/customerModel.js",
    "/purchaseOrder/customer/customerForm.js",
    "/vueSystem/mixins/tablePaginationMixin.js",
    "/warehouse/finishProductOut/instalmentOut/index.js",
    "/warehouse/finishProductOut/instalmentOut/instalmentOutMixin.js"
  ]);

</script>
<script src="./outWarehouseDetail.js"></script>
<script>
  var app = new Vue({
    el: '#app',

    mixins: [
      tablePaginationMixin(),
      instalmentOutMixin
    ],

    data: function () {
      var search = {
        orderId: '',
        companyOrderId: '',
        customerOrderId: '',
        factoryNo: '',
        customerNo: ''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['orderId', 'companyOrderId', 'customerOrderId', 'factoryNo', 'customerNo'],
        productList: [],
        selectProductList: [],
        selfApprovalPermission: false,
        customerNameList: [],
        unitList: [],
        openDetailDialog: false,
        openCustomerDialog: false,
        selectProduct: null,
        customer: null,
        user: null,
        i18n: i18n
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setUnitList(),
        this.setUser(),
        this.checkApprovalPermission(),
        this.setCustomerNameList()
      ]).then(function () {
        return self.setProductList(true, false).then(function () {
          self.loading = false;
        });
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUnitList: function () {
        var self = this;
        return DropdownUtil.getUnitList().then(function (unitList) {
          self.unitList = unitList;
          return unitList;
        });
      },

      checkApprovalPermission: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(6).then(function (hasApproval) {
          self.selfApprovalPermission = hasApproval;
          return hasApproval;
        });
      },

      setCustomerNameList: function () {
        var self = this;
        return DropdownUtil.getCustomerNameAndCodeList({
          type: 2
        }).then(function (customerList) {
          var customerNameList = _.map(customerList, 'customerName');
          self.customerNameList = customerNameList;
          return customerNameList;
        });
      },

      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      setProductList: function (isSearch, hasLoading) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        if (hasLoading === undefined) {
          hasLoading = true;
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        };

        var search = this.search;
        var fields = ['orderId', 'companyOrderId', 'customerOrderId', 'factoryNo', 'customerNo'];
        SysUtil.setPostData(postData, search, fields);

        var user = this.user;
        var type = user.companyInfo.type;
        var inOutUnit;
        if (type === 2) {
          inOutUnit = '台';
        } else {
          inOutUnit = '付';
        }

        if (hasLoading) {
          this.loading = true;
        }
        var self = this;
        return ajaxRequest("companyMaterial/getFinishStockCount", postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var productList = res.returnData;
          for (var i = 0; i < productList.length; i++) {
            var product = productList[i];
            product.customerName = '';
            product.remark = '';
            product.outCountPrice = undefined;
            product.realCount = product.outCount + product.otherGivethisCount;
            product.inOutUnit = inOutUnit;
            product.inOutMoney = 0;
            product.instalmentInfo = null;

            if (product.listMaterial === null) {
              product.listMaterial = [];
            }
          }

          self.productList = productList;
          self.pagination.totalCount = res.iTotalRecords;
          if (hasLoading) {
            self.loading = false;
          }
          return productList;
        }).catch(function () {
          if (hasLoading) {
            self.loading = false;
          }
          return [];
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setProductList(true);
      },

      pageChange: function () {
        this.setProductList();
      },

      toSelectProductList: function (selection) {
        this.selectProductList = selection;
      },

      tableCellClass: function (option) {
        var column = option.column;
        var columnKey = column.columnKey;
        if (columnKey !== 'realCount') {
          return null;
        }

        var product = option.row;
        if (product.realCount > 0) {
          return 'table-btn';
        }
        return null;
      },

      tableRowClick: function (product, column) {
        var columnKey = column.columnKey;
        if (columnKey === 'realCount') {
          this.lookDetail(product);
        }
      },

      lookDetail: function (product) {
        if (product.realCount === 0) {
          return;
        }

        this.selectProduct = product;
        this.openDetailDialog = true;
      },

      outWarehouse: function (product, isAduit) {
        var postData = this.getPostData(product);
        if (postData === null) {
          return;
        }
        postData.isAduit = isAduit;
        this.loading = true;
        var self = this;
        ajaxRequest("companyMaterial/finishStockOut", postData).then(function (msg) {
          self.$alert(msg, '信息', {
            callback: function () {
              self.setProductList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      outWarehouseList: function (isAduit) {
        var productList = this.selectProductList;
        if (productList.length === 0) {
          return;
        }

        var products = [];
        for (var i = 0; i < productList.length; i++) {
          var product = productList[i];
          var productPostData = this.getPostData(product);
          if (productPostData === null) {
            return;
          }
          products.push(productPostData);
        }

        var postData = {
          jsonArray: JSON.stringify(products),
          isAduit: isAduit
        };

        this.loading = true;
        var self = this;
        ajaxRequest('companyMaterial/finishStockOutAll', postData).then(function (msg) {
          self.$alert(msg, '信息', {
            callback: function () {
              self.setProductList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      getPostData: function (product) {
        var requiredFields = ['customerName', 'outCountPrice', 'count', 'inOutMoney', 'inOutUnit'];
        var postData = {
          otherOrderId: product.orderId,
          outCount: product.count
        };
        this.setInstalmentOutPostData(postData, product);
        for (var i = 0; i < requiredFields.length; i++) {
          var field = requiredFields[i];
          var value = product[field];
          if (SysUtil.isEmpty(value)) {
            this.$alert(i18n.getMsg(`warehouse.error.${field}`), '信息')
            return null;
          }
          postData[field] = value;
        }

        postData.inCountPrice = postData.outCountPrice;
        delete postData.outCountPrice;

        var fields = ['orderId', 'type', 'rowIndexs', 'remark'];
        SysUtil.setPostData(postData, product, fields, false, true);
        return postData;
      },

      addCustomer: function () {
        var customer = new Customer({
          type: 2,
          status: '使用'
        });
        this.customer = customer;
        this.openCustomerDialog = true;
      },

      addCustomerSuccess: function () {
        this.openCustomerDialog = false;
        this.loading = true;
        var self = this;
        this.setCustomerNameList().then(function () {
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      unitPriceChange: function (product) {
        var count = product.count;
        var unitPrice = product.outCountPrice;
        var totalMoney = SysUtil.calPrice(count, unitPrice, 'total');
        product.inOutMoney = totalMoney;
      },

      totalMoneyChange: function (product) {
        var count = product.count;
        var totalMoney = product.inOutMoney;
        var unitPrice = SysUtil.calPrice(count, totalMoney, 'unit', 4);
        product.outCountPrice = unitPrice;
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SysCommonSearch: SysCommonSearch,
      OutWarehouseDetail: OutWarehouseDetail,
      CustomerForm: CustomerForm
    }
  });

</script>
<style>
  .product-sale {
    padding: 10px 20px 5px;
    height: calc(100% - 15px);
    position: relative;
    display: flex;
    flex-direction: column;
  }

  .product-sale .product-sale-table-div {
    flex: 1;
    overflow: auto;
  }

  .product-sale .table-btn {
    color: #409eff;
    cursor: pointer;
  }

  .product-sale .product-sale-instalment {
    cursor: pointer;
  }

  .product-sale .product-sale-instalment a{
    text-decoration: none;
    border-bottom: 1px solid;
  }

  .product-sale .product-sale-instalment a:link{
    color: #0000ee;
  }

</style>

</html>
